<!-- 事件日志 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset">
        <el-button type="primary" size="small" @click="lowConfigurationDefinition">低配定义</el-button>
      </connsearch>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;"  @tab-click="tabClick">
          <!-- <el-tab-pane label="按所在分区统计分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart  :chartData="pie1Data" @pieclick="echartsClick" title="按所在分区统计分析"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="按所在校区统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie2Data" @pieclick="echartsClick" title="按所在校区统计分析"/>
            </el-col>
          </el-tab-pane> -->
          <el-tab-pane label="按资产健康统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie3Data" @pieclick="echartsClick" title="按资产健康统计分析"/>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <!-- <el-table-column label="所在分区" prop="PrimArea" width="150" align="left" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.PrimArea }} / {{ row.SecondArea }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所在校区" show-overflow-tooltip prop="SchoolName" align="left">
            <template slot-scope="{row}">
              <span>{{ row.SchoolName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" align="left">
            <template slot-scope="{row}">
              <span>{{ row.DeviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上报时间" show-overflow-tooltip prop="TransTime" align="left"></el-table-column>
          <el-table-column label="资产总结" show-overflow-tooltip prop="Status" align="left" width="100">
            <template slot-scope="{row}">
              <span style="color:#67C23A" v-show="row.Status === 1">标准资产</span>
              <span style="color:#E6A23C" v-show="row.Status === 2">低配资产</span>
              <span style="color:#F56C6C" v-show="row.Status === 3">高龄资产</span>
              <span style="color:#909399" v-show="row.Status === 4">高龄低配</span>
            </template>
          </el-table-column>
          <el-table-column label="使用年份" show-overflow-tooltip prop="StartDate" align="left"></el-table-column>
          <!-- <el-table-column label="主板" show-overflow-tooltip prop="Mainboard" align="left"></el-table-column> -->
          <!-- <el-table-column label="cpu" show-overflow-tooltip prop="Cpu" align="left"></el-table-column> -->
          <el-table-column label="核数" show-overflow-tooltip prop="CpuCoreCount" align="left"></el-table-column>
          <el-table-column label="主频" show-overflow-tooltip prop="CpuHZ" align="left">
            <template slot-scope="{row}">
              <span>{{ row.CpuHZ }} GHz</span>
            </template>
          </el-table-column>
          <el-table-column label="内存" show-overflow-tooltip prop="MemSize" align="left"></el-table-column>
          <el-table-column label="系统磁盘" show-overflow-tooltip prop="SysDiskSize" align="left"></el-table-column>
          <el-table-column label="数据磁盘" show-overflow-tooltip prop="ExtDiskSize" align="left"></el-table-column>
          <el-table-column label="操作" width="80px" align="left" fixed="right" >
              <template slot-scope="scope">
                <el-button size="mini" type="success" @click="detailsChange(scope.row)">详情</el-button>
              </template>
            </el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="低配定义"
      :visible.sync="logDialog"
      v-el-drag-dialog
      width="800px">
      <el-form label-width="170px" :model="resourceForm"  ref="resourceForm">
        <el-form-item label='内存小于等于:' prop="Mem">
          <el-input v-model.number="resourceForm.Mem" nameoninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入内存" maxlength="10"><template slot="append">G</template></el-input>
        </el-form-item>
        <el-form-item label='磁盘总空间小于等于:' prop="Disk">
          <el-input v-model.number="resourceForm.Disk" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入磁盘总空间" maxlength="10"><template slot="append">G</template></el-input>
        </el-form-item>
        <el-form-item label='cpu核数小于等于:' prop="CpuCoreCount">
          <el-input v-model.number="resourceForm.CpuCoreCount" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入cpu核数" maxlength="10"><template slot="append">个</template></el-input>
        </el-form-item>
        <el-form-item label='cpu主频小于等于:' prop="CpuHZ">
          <el-input v-model="resourceForm.CpuHZ" oninput="value=value.replace(/[^\d.]/g,'')" placeholder="请输入cpu主频" maxlength="10"><template slot="append">GHz</template></el-input>
        </el-form-item>
        <el-form-item label='高龄资产定义:' prop="Age">
          <el-input v-model.number="resourceForm.Age" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入超过多少年" maxlength="10"><template slot="append">年</template></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="logDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog v-el-drag-dialog title="资产详情" :close-on-click-modal="false" :visible.sync="dialogTableVisible"  width="70%">
        <HardDetail :DeviceObj = DeviceObj></HardDetail>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogTableVisible = false;">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import { getNowDay, parseTime, formatTime2, formatTime3, formatBytes2 } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import HardDetail from "@/components/HardDetail"
import { connrequest } from "@/api/firstPage.js"
export default {
  directives: { elDragDialog },
  components: { connsearch, barchart, piechart,HardDetail },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按资产健康统计分析',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      logDialog: false,
      dialogTableVisible: false,
      tab: false,
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      tableData:[],
      searchform:{},
      options:{},
      searchobj: {},
      resourceForm: {},
      DeviceObj: {},
      formOptions: [
        {
          col: 8,
          label: "资产选择",
          prop:"DeviceName",
          element: "el-select",
          initValue: "",
          placeholder: "请选择资产",
          options:[],
          events: {
            input(val) {
              that.searchform.DeviceName = val
            },
          },
        },
        {
          col: 4,
          hidden: false,
          label: "资产类型", // label文字
          prop: "Status", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 0, // 字段初始值,
          placeholder: "请选择严重性等级", // elementui组件属性
          options: [
            { label: '全部', value: 0 },
            { label: '标准资产', value: 1 },
            { label: '低配资产', value: 2 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Status = val
            },
          },
        },
        {
          col: 4,
          hidden: false,
          label: "高龄资产", // label文字
          prop: "Age", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 0, // 字段初始值,
          placeholder: "请选择高龄资产", // elementui组件属性
          options: [
            { label: '全部', value: 0 },
            { label: '标准资产', value: 1 },
            { label: '高龄资产', value: 2 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Age = val
            },
          },
        },
        {
          col: 8,
          label: "主板关键字",
          prop: "KeyMainboard",
          element: "el-input",
          placeholder: "请输入主板关键字",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.KeyMainboard = val
            },
          },
        },
        {
          col: 8,
          label: "cpu关键字",
          prop: "KeyCpu",
          element: "el-input",
          placeholder: "请输入cpu关键字",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.KeyCpu = val
            },
          },
        },
        {
          col: 8,
          label: "内存关键字",
          prop: "KeyMem",
          element: "el-input",
          placeholder: "请输入内存关键字",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.KeyMem = val
            },
          },
        },
        {
          col: 8,
          label: "磁盘关键字",
          prop: "KeyDisk",
          element: "el-input",
          placeholder: "请输入磁盘关键字",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.KeyDisk = val
            },
          },
        },
        
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    let arr = [ parseTime(startTime), '']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.$set(this.searchform,'Status', 0)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    // this.GetDeviceStatusSumTree()
    this.CenterGetDevice()
  },
  methods: {
    async CenterGetDevice(){
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000000
        },
        Filter:{
          Status: 0,
        }
      }
      const res = await connrequest('CenterGetDevice', data)
      let assetList = []
      res.Data.map(item => {
        assetList.push({ label: item.DeviceName, value: item.DeviceName })
      })
      this.formOptions.map( item => {
        if(item.label === '资产选择'){
          item.options = assetList
        }
      })
    },
    // 获取子节点的资产
    async lazyLoad(node, resolve){
      if(node.level < 4){
        resolve(node.data) 
      }else{
        const data = {
          Paging:{
            QueryPageNo: 1,
            QueryPageLength: 100000
          },
          Filter:{
            SchoolName: node.label,
          }
        }
        const res = await connrequest('CenterGetDevice', data)
        let arr = []
        res.Data.map(item => {
          arr.push( {SubClass: item.DeviceName, value: item.DeviceName, level: 5, children: undefined} )
        })
        resolve(arr) 
      }
    },
    transformData(inputData) {
      const { RootName, PrimArea} = inputData;
        return {
          SubClass: RootName,
          value: RootName,
          level: 1,
          children: PrimArea.map(area => ({
            SubClass: area.PrimAreaName,
            value: area.PrimAreaName,
            level: 2,
            children: area.SecondArea.map(secondArea => ({
              SubClass: secondArea.SecondAreaName,
              value: secondArea.SecondAreaName,
              level: 3,
              children: secondArea.School.map(School => ({
                SubClass: School.SchoolName,
                level: 4,
              }))
          }))
        }))
      }
    },
    // 获取资产树
    async GetDeviceStatusSumTree() {
      const res = await connrequest('GetDeviceStatusSumTree')
      this.formOptions.map( item => {
        if(item.label === '资产选择'){
          item.options = [this.transformData(res.Data)]
        }
      })
    },
    async lowConfigurationDefinition(){
      const res = await connrequest('GetPCLowerStandard')
      this.resourceForm = {...res.Data, Disk: res.Data?.Disk / 1000 || 0, Mem: res.Data?.Mem / 1000 || 0, CpuHZ: res.Data?.CpuHZ / 1000 || 0}
      this.logDialog = true
    },
    async submit(){
      const data = { 
        Data:{
          ...this.resourceForm,
          Disk: this.resourceForm.Disk * 1000,
          Mem: this.resourceForm.Mem * 1000,
          CpuHZ: this.resourceForm.CpuHZ * 1000,
          totalDiskSpace: this.resourceForm.totalDiskSpace * 1024
        }
      }
      const res = await connrequest('SetPCLowerStandard', data)
      this.logDialog = false
    },
    detailsChange(row){
      this.dialogTableVisible = true
      this.DeviceObj = { 
        control:true,
        ...row,
      }
    },
    handleChange(){},
    // 获取所有数据
    getData(){
      this.GetEventLog()
      switch (this.tabTitle) {
        case '按所在分区统计分析':
          this.GetDeviceHardwareSumGroupByArea()
          break;
        case '按所在校区统计分析':
          this.GetDeviceHardwareSumGroupBySchool()
          break;default:
          this.GetDeviceHardwareSumGroupByHealth()
          break;
      }
    },
    echartsClick(val,title){
      this.pageNum = 1
      if(title === '按所在分区统计分析'){
        this.searchobj = { PrimArea: val.split('_')[0], SecondArea: val.split('_')[1] }
        this.GetEventLog(this.searchobj)
      }else if(title === '按所在校区统计分析'){
        this.searchobj = { SchoolName: val }
        this.GetEventLog(this.searchobj)
      }else{
        let asset = {}
        if (val === '标准资产'){
          asset = {Status: 1, Age: 1}
        }else if(val === '低配资产'){
          asset = {Status: 2, Age: 1}
        }else if(val === '高龄资产'){
          asset = {Status: 1, Age: 2}
        }else if(val === '高龄低配'){
          asset = {Status: 2, Age: 2}
        }
        this.searchobj = { ...asset }
        this.GetEventLog(this.searchobj)
      }
      // this.GetEventLog()
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (row.label) {
        case '按所在分区统计分析':
          this.GetDeviceHardwareSumGroupByArea()
          break;
        case '按所在校区统计分析':
          this.GetDeviceHardwareSumGroupBySchool()
          break;default:
          this.GetDeviceHardwareSumGroupByHealth()
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          DeviceName: this.searchform.DeviceName,
          DeviceID: this.searchform.DeviceID,
          KeyMainboard: this.searchform.KeyMainboard,
          KeyMem: this.searchform.KeyMem,
          KeyCpu: this.searchform.KeyCpu,
          KeyDisk: this.searchform.KeyDisk,
          Status:this.searchform.Status,
          Age:this.searchform.Age,
          ...searchobj
        }
      }
      const res = await connrequest('GetDeviceHardware', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        item.StartDate = item.StartDate ? formatTime3(item.StartDate) : '未知'
        item.MemSize = formatBytes2(item.MemSize * 1000000)
        item.SysDiskSize = formatBytes2(item.SysDiskSize * 1000000)
        item.ExtDiskSize = formatBytes2(item.ExtDiskSize * 1000000)
        item.CpuHZ = (item.CpuHZ / 1000).toFixed(2)
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging?.TotalCount || 0
    },
    // 按所在分区统计分析
    async GetDeviceHardwareSumGroupByArea(){
      let arr = []
      const data = {
        Filter:{
          DeviceName: this.searchform.DeviceName,
          DeviceID: this.searchform.DeviceID,
          KeyMainboard: this.searchform.KeyMainboard,
          KeyMem: this.searchform.KeyMem,
          KeyCpu: this.searchform.KeyCpu,
          KeyDisk: this.searchform.KeyDisk,
          Status:this.searchform.Status,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetDeviceHardwareSumGroupByArea', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie1Data = arr
    },
    // 按所在校区统计分析
    async GetDeviceHardwareSumGroupBySchool(){
      let arr = []
      const data = {
        Filter:{
          DeviceName: this.searchform.DeviceName,
          DeviceID: this.searchform.DeviceID,
          KeyMainboard: this.searchform.KeyMainboard,
          KeyMem: this.searchform.KeyMem,
          KeyCpu: this.searchform.KeyCpu,
          KeyDisk: this.searchform.KeyDisk,
          Status:this.searchform.Status,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetDeviceHardwareSumGroupBySchool', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie2Data = arr
    },
    // 按事件资产统计分析
    async GetDeviceHardwareSumGroupByHealth(){
      let arr = []
      const data = {
        Filter:{
          DeviceName: this.searchform.DeviceName,
          DeviceID: this.searchform.DeviceID,
          KeyMainboard: this.searchform.KeyMainboard,
          KeyMem: this.searchform.KeyMem,
          KeyCpu: this.searchform.KeyCpu,
          KeyDisk: this.searchform.KeyDisk,
          Status:this.searchform.Status,
          Age:this.searchform.Age,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetDeviceHardwareSumGroupByHealth', data)
      let Device = res.Data?.Device || {}
      arr.push(
        {name: '标准资产', value: Device.HealthDeviceCount || 0},
        {name: '低配资产', value: Device.LowerDeviceCount || 0},
        {name: '高龄低配', value: Device.LowerOldDeviceCount || 0},
        {name: '高龄资产', value: Device.OldDeviceCount || 0},
      )
      this.pie3Data = arr
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = {...val}
      // if(this.searchform.timeRange){
      //   this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      // }
      this.getData()
    },
    // 重置
    reset(){
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "资产类型"){
          item.initValue = 0
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'Status', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({...this.searchobj})
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetEventLog({...this.searchobj})
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>